package com.atguigu.meinian.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.meinian.constant.MessageConstant;
import com.atguigu.meinian.exception.MeiNainException;
import com.atguigu.meinian.pojo.OrderSetting;
import com.atguigu.meinian.service.OrdersettingService;
import com.atguigu.meinian.util.POIUtils;
import com.atguigu.meinian.vo.R;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;

/**
 * @author zbystart
 * @create 2021-06-23 8:36
 */
@RestController
@RequestMapping("/ordersetting")
public class OrdersettingController {

    @Reference
    private OrdersettingService ordersettingService;

    @PostMapping("/upload")
    public R upload(MultipartFile excelFile) {
        List<String[]> list = null;
        try {
            // 解析上传过来的表格数据
            list = POIUtils.readExcel(excelFile);
            saveExcelToDB(list);
        } catch (MeiNainException e) {
            return R.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(MessageConstant.PIC_UPLOAD_FAIL);
        }
        return R.ok(MessageConstant.UPLOAD_SUCCESS,null);
    }

    @GetMapping("/by/month/list")
    public R list(String date) {
        try {
            // 查出这一月预约数据
            List<Map<String,Integer>> data =  ordersettingService.getOrdersettingByMonth(date);
            return R.ok(MessageConstant.GET_ORDERSETTING_SUCCESS,data);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(MessageConstant.GET_ORDERSETTING_FAIL);
        }

    }

    @PostMapping("/editNumberByDate")
    public R editNumberByDate(@RequestBody Map<String,String> map) {
        try {
            ordersettingService.updateNumberByDate(map.get("orderDate"),Integer.valueOf(map.get("number")));
            return R.ok(MessageConstant.ORDERSETTING_SUCCESS,null);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(MessageConstant.ORDERSETTING_FAIL);
        }
    }

    private void saveExcelToDB(List<String[]> list) {
        if (list.size() > 0) {
            ordersettingService.saveExcelToDB(list);
            return;
        }
        throw new MeiNainException("表格数据为空");
    }
}
